<template>
  <div class="codes_container">
    <div v-loading="getCodeListLoading" class="body" element-loading-text="加载中...">
      <div ref="headerRef" class="header">
        <div class="btn_group">
          <HPlainButton v-permission="'code_add'" @click="createDialog = true">
            创建序列号
          </HPlainButton>
          <HPlainButton v-permission="'code_import'" @click="onImportCode">导入序列号</HPlainButton>
          <!-- <HPlainButton v-permission="'code_export'" @click="onExportCode">导出序列号</HPlainButton> -->
          <el-dropdown trigger="click">
            <HButton :disabled="activeId.length == 0">
              批量操作
              <el-icon class="el-icon--right">
                <arrow-down />
              </el-icon>
            </HButton>
            <template #dropdown>
              <el-dropdown-menu>
                <div v-permission="'code_active'">
                  <el-dropdown-item @click="handleClick(1)">
                    <el-icon>
                      <CircleCheck />
                    </el-icon>
                    批量激活
                  </el-dropdown-item>
                </div>

                <div v-permission="'code_del'">
                  <el-dropdown-item @click="handleClick(2)">
                    <el-icon>
                      <Delete />
                    </el-icon>
                    批量删除
                  </el-dropdown-item>
                </div>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
        <!-- 搜索条件 -->
        <div class="search">
          <!-- 日期范围 -->
          <DateRange
            ref="dateRangeRef"
            start-date-placeholder="创建开始时间"
            end-date-placeholder="创建结束时间"
            @change="handleDateChange"
          />

          <!-- <DateRange
            ref="dateRangeRef2"
            start-date-placeholder="出厂开始日期"
            end-date-placeholder="出厂结束日期"
            @change="handleDateChange2"
          /> -->

          <DateRange
            start-date-placeholder="出库开始日期"
            end-date-placeholder="出库结束日期"
            @change="handleOutWarehouseDateChange"
          />

          <!--审核状态-->
          <el-select
            v-model="getListParam.applyState"
            placeholder="请选择审核状态"
            clearable
            style="width: 140px"
            @change="getList"
            @clear="getList"
          >
            <el-option :value="0" label="待审核" />
            <el-option :value="1" label="审核通过" />
            <el-option :value="2" label="驳回" />
          </el-select>

          <!-- 物料类型 -->
          <el-select
            v-model="getListParam.type"
            style="width: 100px"
            placeholder="物料类型"
            filterable
            clearable
            @change="getCodeList"
          >
            <el-option :value="0" label="空码" />
            <el-option :value="1" label="成品" />
            <el-option :value="2" label="物料" />
            <el-option :value="3" label="备用机" />
          </el-select>

          <el-select
            v-model="getListParam.status"
            placeholder="质保状态"
            style="width: 100px"
            clearable
            @change="getCodeList"
          >
            <el-option :value="1" label="未质保" />
            <el-option :value="2" label="质保中" />
            <el-option :value="3" label="已过保" />
          </el-select>

          <el-select
            v-model="getListParam.storestatus"
            placeholder="出库状态"
            style="width: 120px"
            clearable
            @change="getCodeList"
          >
            <el-option :value="1" label="未出入库" />
            <!-- <el-option :value="2" label="预入库" /> -->
            <el-option :value="3" label="已入库" />
            <!-- <el-option :value="4" label="预出库" /> -->
            <el-option :value="5" label="已出库" />
          </el-select>

          <!-- 物料品牌 -->
          <!-- <el-select
            v-model="getListParam.brandId"
            :filter-method="remoteMethod"
            :loading="loading2"
            remote-show-suffix
            placeholder="物料品牌"
            filterable
            clearable
            style="width: 100px"
            @change="getCodeList"
          >
            <el-option
              v-for="(item, index) in brandData"
              :key="index"
              :value="item.id"
              :label="item.name"
            />
          </el-select> -->

          <!-- 物料分类 -->
          <!-- <el-select v-model="typeId" placeholder="物料分类" :filter-method="remoteMethod2" :loading="loading3"
            @change="getList" filterable clearable remote-show-suffix style="width: 100px">
            <el-option v-for="(item, index) in typeData" :key="index" :value="item.id" :label="item.name" />
          </el-select> -->

          <!-- 物料分类 -->
          <el-cascader
            ref="cascader"
            v-model="getListParamTypes"
            clearable
            :props="CascaderProps"
            :options="goodsTypeList"
            style="width: 140px"
            placeholder="物料分类"
            @change="onChangeGoodType"
          >
            <template #default="{ node, data }">
              <span>{{ data.name }}</span>
              <span v-if="!node.isLeaf"> ({{ data.childData.length }}) </span>
            </template>
          </el-cascader>

          <!--序列号来源-->
          <el-select
            v-model="getListParam.codeSource"
            placeholder="请选择序列号来源"
            clearable
            style="width: 140px"
            @change="getCodeList"
            @clear="getCodeList"
          >
            <el-option :value="1" label="系统创建" />
            <el-option :value="2" label="系统导入" />
            <el-option :value="3" label="工单报单创建" />
            <el-option :value="5" label="金蝶云星空" />
          </el-select>

          <!-- 物料名称 -->
          <el-input
            v-model.trim="getListParam.goodsName"
            clearable
            placeholder="物料名称"
            style="width: 170px"
            @keyup.enter="getCodeList"
            @clear="getCodeList"
          />

          <!-- 物料编号 -->
          <el-input
            v-model.trim="getListParam.goods"
            clearable
            placeholder="物料编号"
            style="width: 170px"
            @keyup.enter="getCodeList"
            @clear="getCodeList"
          />

          <!-- 物料型号 -->
          <el-input
            v-model.trim="getListParam.goodsModel"
            clearable
            placeholder="物料型号"
            style="width: 170px"
            @keyup.enter="getCodeList"
            @clear="getCodeList"
          />

          <!-- 物料规格 -->
          <el-input
            v-model.trim="getListParam.goodsSpec"
            clearable
            placeholder="物料规格"
            style="width: 170px"
            @keyup.enter="getCodeList"
            @clear="getCodeList"
          />

          <!-- 防伪序列号 -->
          <el-input
            v-model.trim="getListParam.code"
            style="width: 190px"
            clearable
            placeholder="防伪序列号"
            @keyup.enter="getCodeList"
            @clear="getCodeList"
          />

          <!-- 合同号 -->
          <el-input
            v-model.trim="getListParam.contractNo"
            style="width: 140px"
            clearable
            placeholder="合同号"
            @keyup.enter="getCodeList"
            @clear="getCodeList"
          />

          <!-- 发货单号 -->
          <!-- <el-input
            v-model.trim="getListParam.sendGoodsNumber"
            style="width: 190px"
            clearable
            placeholder="发货单号"
            @keyup.enter="getCodeList"
            @clear="getCodeList"
          /> -->

          <!-- 销货单号 -->
          <!-- <el-input
            v-model.trim="getListParam.outboundCode"
            style="width: 190px"
            clearable
            placeholder="销货单号"
            @keyup.enter="getCodeList"
            @clear="getCodeList"
          /> -->

          <HButton type="primary" @click="getCodeList">
            <el-icon>
              <Search />
            </el-icon>
            搜索
          </HButton>
          <HButton @click="onReset">
            <el-icon>
              <RefreshRight />
            </el-icon>
            重置
          </HButton>
        </div>
      </div>
      <div class="table-footer">
        <div class="table">
          <el-table
            :border="true"
            stripe
            resizable
            :data="codeList"
            height="100%"
            @cell-dblclick="goDetail"
            @selection-change="changeAll"
          >
            <el-table-column type="selection" width="40" fixed />

            <!-- 序号 -->
            <el-table-column width="50" label="序号" fixed="left" type="index" :align="'center'" />

            <!-- 序列号  -->
            <el-table-column
              label="序列号"
              show-overflow-tooltip
              prop="securityCode"
              fixed
              width="180"
            >
              <template #default="{ row }">
                <div style="display: flex; column-gap: 6px">
                  <div v-if="row.applyState === 0" style="color: #e69103">待审核</div>
                  <div v-if="row.applyState === 2" style="color: #f56c6c">驳回</div>
                  <HLink @click="goDetail(row)">
                    {{ row.securityCode }}
                  </HLink>
                </div>
              </template>
            </el-table-column>

            <!-- 批次号  格美淇先隐藏-->
            <!-- <el-table-column show-overflow-tooltip prop="batchCode" label="批次编号" width="150" /> -->

            <!-- 设备属性 -->
            <el-table-column show-overflow-tooltip label="设备属性" width="74">
              <template #default="{ row }">
                {{ row.isStandby === 1 ? '备用机' : '' }}
              </template>
            </el-table-column>

            <!-- 物料编号 -->
            <el-table-column show-overflow-tooltip prop="goodsCode" label="物料编号" width="150" />

            <!-- 物料信息 -->
            <el-table-column
              show-overflow-tooltip
              prop="brand goodsSpecName goodsName goodsModel"
              label="物料信息"
              width="200"
            >
              <template #default="{ row }">
                <div style="white-space: nowrap; overflow: hidden; text-overflow: ellipsis">
                  {{ row.goodsName }}
                </div>
              </template>
            </el-table-column>

            <!-- 物料规格 -->
            <el-table-column
              show-overflow-tooltip
              prop="goodsSpecName"
              label="物料规格"
              width="120"
            />

            <!-- 合同号 -->
            <el-table-column show-overflow-tooltip prop="contractNo" label="合同号" width="150" />

            <!-- 发货单号 -->
            <!-- <el-table-column
            show-overflow-tooltip
            prop="sendGoodsNumber"
            label="发货单号"
            width="120"
          /> -->

            <!-- 出厂日期 -->
            <!-- <el-table-column
            show-overflow-tooltip
            prop="dateOfProduction"
            label="出厂日期"
            width="130"
          /> -->

            <!-- 销货单号 -->
            <!-- <el-table-column show-overflow-tooltip prop="outboundcode" label="销货单号" width="120" /> -->

            <!-- 公司信息 -->
            <el-table-column show-overflow-tooltip label="公司信息" width="200">
              <template #default="scope">
                {{ scope.row.username }}&nbsp;{{ scope.row.phone }}
              </template>
            </el-table-column>

            <!-- 仓储序列号 -->
            <!-- <el-table-column
              show-overflow-tooltip
              prop="outboundStoreNumber"
              label="出库仓编号"
              width="100"
            /> -->

            <!-- 备注 -->
            <!-- <el-table-column show-overflow-tooltip prop="remark" label="备注" width="120" /> -->

            <!-- 销售部门编号 -->
            <!-- <el-table-column
            show-overflow-tooltip
            prop="saleNetworkNumber"
            label="销售部门编号"
            width="120"
          /> -->

            <!-- 出库部门 -->
            <!-- <el-table-column
            show-overflow-tooltip
            prop="saleNetworkName"
            label="销售部门"
            width="140"
          /> -->

            <!-- 销售金额 -->
            <!-- <el-table-column show-overflow-tooltip prop="salePrice" label="销售金额" width="100">
              <template #default="i"> ￥{{ Number(i.row.salePrice).toFixed(2) }} </template>
            </el-table-column> -->

            <!-- 序列号来源 -->
            <el-table-column label="序列号来源" width="118">
              <template #default="scope">
                <span v-if="scope.row.codeSource === 1">系统创建</span>
                <span v-if="scope.row.codeSource === 2">系统导入</span>
                <span v-if="scope.row.codeSource === 3">工单报单创建</span>
                <!-- <span v-if="scope.row.codeSource === 4">用友ERP</span> -->
                <span v-if="scope.row.codeSource === 5">金蝶云星空</span>
              </template>
            </el-table-column>

            <!-- 生产日期 -->
            <!-- <el-table-column
              show-overflow-tooltip
              prop="produceDate"
              label="生产日期"
              width="128"
            /> -->

            <!-- 创建时间 -->
            <el-table-column show-overflow-tooltip prop="createTime" label="创建时间" width="128" />

            <!-- 更新时间 -->
            <el-table-column show-overflow-tooltip prop="updateTime" label="更新时间" width="128" />

            <!-- 出库时间 -->
            <el-table-column
              show-overflow-tooltip
              prop="outboundTime"
              label="出库时间"
              width="128"
            />

            <!-- 质保到期时间 -->
            <el-table-column
              show-overflow-tooltip
              prop="warrantyEndTime"
              label="质保到期时间"
              width="128"
            />

            <!-- 是否激活 -->
            <!-- <el-table-column
            show-overflow-tooltip
            prop="activa"
            label="激活状态"
            width="84"
            fixed="right"
            :align="'center'"
          >
            <template #default="scope">
              <div class="flex_justify_center">
                <HStatus v-if="scope.row.activa" type="success">已激活</HStatus>
                <HStatus v-else type="info">未激活</HStatus>
              </div>
            </template>
          </el-table-column> -->

            <!-- 质保状态 -->
            <el-table-column
              prop="status"
              label="质保状态"
              width="84"
              fixed="right"
              :align="'center'"
            >
              <template #default="scope">
                <div class="flex_justify_center">
                  <HStatus v-if="scope.row.status === 3" type="info">已过保</HStatus>
                  <HStatus v-if="scope.row.status === 2">质保中</HStatus>
                  <HStatus v-if="scope.row.status === 1" type="info">未质保</HStatus>
                  <HStatus v-if="scope.row.status === 4" type="error">已作废</HStatus>
                </div>
              </template>
            </el-table-column>

            <!-- 出库状态 -->
            <el-table-column
              prop="status"
              label="出库状态"
              width="120"
              fixed="right"
              :align="'center'"
            >
              <template #default="scope">
                <div class="flex_justify_center">
                  <HStatus v-if="scope.row.storeStatus === 1" type="info">未出入库</HStatus>
                  <HStatus v-if="scope.row.storeStatus === 2" type="warning">预入库</HStatus>
                  <HStatus v-if="scope.row.storeStatus === 3" type="success">已入库</HStatus>
                  <HStatus v-if="scope.row.storeStatus === 4" type="warning">预出库</HStatus>
                  <HStatus v-if="scope.row.storeStatus === 5" type="success">已出库</HStatus>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div ref="paginationRef" class="pagination">
          <Pagination
            ref="paginationInstance"
            :list_total="total"
            @size-change="getCodeList"
            @current-change="getCodeList"
          />
        </div>
      </div>

      <!-- 创建序列号弹窗 -->
      <CreateCodepopup v-model="createDialog" @update="getCodeList" />

      <!-- 导出序列号弹窗-->
      <h-dialog
        v-model="exportCodeModalState"
        title="导出序列号"
        :loading="exportLoading"
        :content-padding-top="30"
        :width="800"
        @close="hideExportModal"
      >
        <div class="export_code_modal">
          <div class="tip"> 默认不筛选条件，将导出全部数据！ </div>
          <div class="export_code_modal_form_content">
            <div class="date_range">
              <!-- 创建日期范围 -->
              <DateRange
                ref="dateRangeRef"
                start-date-picker-width="244px"
                end-date-picker-width="244px"
                start-date-placeholder="创建开始时间"
                end-date-placeholder="创建结束时间"
                @change="handleChangeExportParamCreateDateRange"
              />
            </div>

            <div class="date_range">
              <!-- 出厂日期范围 -->
              <!-- <DateRange
                ref="dateRangeRef2"
                start-date-picker-width="244px"
                end-date-picker-width="244px"
                start-date-placeholder="出厂开始日期"
                end-date-placeholder="出厂结束日期"
                @change="handleChangeExportParamLeaveFactoryDateRange"
              /> -->
            </div>

            <div class="grid-layout">
              <!-- 物料类型 -->
              <el-select v-model="exportParam.type" placeholder="物料类型" filterable clearable>
                <el-option :value="1" label="成品" />
                <el-option :value="2" label="物料" />
              </el-select>

              <!-- 物料品牌 -->
              <el-select
                v-model="exportParam.brandId"
                :filter-method="remoteMethod"
                :loading="loading2"
                remote-show-suffix
                placeholder="物料品牌"
                filterable
                clearable
              >
                <el-option
                  v-for="(item, index) in brandData"
                  :key="index"
                  :value="item.id"
                  :label="item.name"
                />
              </el-select>

              <!-- 物料分类 -->
              <el-cascader
                ref="cascader"
                v-model="exportParamTypes"
                clearable
                :props="CascaderProps"
                :options="goodsTypeList"
                placeholder="物料分类"
                @change="onChangeExportParamGoodType"
              >
                <template #default="{ node, data }">
                  <span>{{ data.name }}</span>
                  <span v-if="!node.isLeaf"> ({{ data.childData.length }}) </span>
                </template>
              </el-cascader>

              <!-- 物料名称 -->
              <el-input v-model.trim="exportParam.goodsName" clearable placeholder="物料名称" />

              <!-- 物料编号 -->
              <el-input v-model.trim="exportParam.goods" clearable placeholder="物料编号" />

              <!-- 物料型号 -->
              <el-input v-model.trim="exportParam.goodsModel" clearable placeholder="物料型号" />

              <!-- 物料规格 -->
              <el-input v-model.trim="exportParam.goodsSpec" clearable placeholder="物料规格" />

              <!-- 防伪序列号 -->
              <el-input v-model.trim="exportParam.code" clearable placeholder="防伪序列号" />

              <!-- 发货单号 -->
              <el-input
                v-model.trim="exportParam.sendGoodsNumber"
                clearable
                placeholder="发货单号"
              />

              <!-- 销货单号 -->
              <el-input v-model.trim="exportParam.outboundCode" clearable placeholder="销货单号" />
            </div>
          </div>
        </div>

        <template #footer>
          <HButton is-modal type="primary" @click="onConfirmExport">导出</HButton>
          <HButton is-modal @click="hideExportModal">取消</HButton>
        </template>
      </h-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
  import Pagination from '@/components/Pagination/index.vue'
  import { ref, onMounted, reactive, watch, onUnmounted } from 'vue'
  import { Search, RefreshRight, CircleCheck, ArrowDown, Delete } from '@element-plus/icons-vue'
  import { useRouter, useRoute } from 'vue-router'
  import { activCode, deleteCode, codeExportExcel } from '@/api/code'
  import { brandPageSelect, typePageSelect, getGoodsType } from '@/api/goodsInfo'
  import { Action, ElMessage, ElMessageBox, MessageBoxState } from 'element-plus'
  import CreateCodepopup from '../../code/list/detail/components/createCodepopup/index.vue'
  import moment from 'moment'
  import DateRange from '@/components/business/date-range/DateRange.vue'
  import _ from 'lodash'
  import { CSSProperties } from 'vue'
  import routeComponentName from '@/config/route-component-name'
  import { useGetCodeList } from '@/services/pages/code/useCodeList'

  const { total, codeList, getCodeListLoading, getListParam, getList, clearGetListParam } =
    useGetCodeList()

  defineOptions({
    name: routeComponentName.snCode.codeList,
  })

  // 当前激活的路由对象
  const route = useRoute()

  // 全局路由对象
  const router = useRouter()

  // 搜索条件 - 物料分类
  const getListParamTypes = ref<Array<string> | null>(null)

  // 导出条件 - 物料分类
  const exportParamTypes = ref<Array<string> | null>(null)

  // 分页组件实例
  const paginationInstance = ref<InstanceType<typeof Pagination> | null>(null)

  // 导出序列号条件
  const exportParam = ref<Omit<CodeAPIRequest.GetCodeList, 'limit' | 'page'>>({
    brandId: '',
    code: '',
    dateOfProductionEndTime: '',
    dateOfProductionStartTime: '',
    endTime: '',
    goods: '',
    goodsModel: '',
    goodsName: '',
    goodsSpec: '',
    outboundCode: '',
    sendGoodsNumber: '',
    startTime: '',
    status: null,
    threeTypeId: '',
    twoTypeId: '',
    type: 1,
    typeId: '',
    storestatus: '',
    snCodeStoreOutboundEndDate: '',
    snCodeStoreOutboundStartDate: '',
    codeSource: '',
    applyState: '',
  })

  const headerRef = ref<HTMLDivElement | null>(null)
  const paginationRef = ref<HTMLDivElement | null>(null)
  const tableStyle = ref<CSSProperties>({})
  const cascader = ref() //分类ref

  // 日期范围选择器组件
  const dateRangeRef = ref<InstanceType<typeof DateRange> | null>(null)
  // const dateRangeRef2 = ref<InstanceType<typeof DateRange> | null>(null)
  const createDialog = ref(false)
  const loading2 = ref(false)
  const brandData = ref(null)
  const typeData = ref(null)
  const exportCodeModalState = ref(false)
  const dataPage = reactive({
    limit: 0,
    name: '',
    page: 0,
  })
  const dataPage2 = reactive({
    limit: 0,
    name: '',
    page: 0,
  })
  const exportLoading = ref(false)
  // ********************级联选择分类*********************
  const CascaderProps = ref({
    value: 'id',
    label: 'name',
    children: 'childData',
    checkStrictly: true,
  })
  // 获取列表
  const goodsTypeList = ref([])

  /**
   * 重置事件
   */
  const onReset = () => {
    if (dateRangeRef.value) {
      dateRangeRef.value.clearDate()
    }
    // if (dateRangeRef2.value) {
    //   dateRangeRef2.value.resetDateRange()
    // }
    clearGetListParam()
    getCodeList()
  }

  /**
   * 物料分类选择事件
   */
  const onChangeGoodType = () => {
    if (!getListParamTypes.value) {
      getListParam.value.typeId = ''
      getListParam.value.twoTypeId = ''
      getListParam.value.threeTypeId = ''
      getCodeList()
      return
    }

    if (getListParamTypes.value) {
      getListParam.value.typeId = getListParamTypes.value[0] || ''
      getListParam.value.twoTypeId = getListParamTypes.value[1] || ''
      getListParam.value.threeTypeId = getListParamTypes.value[2] || ''
      getCodeList()
    }
  }

  /**
   * 导出物料分类选择事件
   */
  const onChangeExportParamGoodType = () => {
    if (!exportParamTypes.value) {
      exportParam.value.typeId = ''
      exportParam.value.twoTypeId = ''
      exportParam.value.threeTypeId = ''
      return
    }

    if (exportParamTypes.value) {
      exportParam.value.typeId = exportParamTypes.value[0] || ''
      exportParam.value.twoTypeId = exportParamTypes.value[1] || ''
      exportParam.value.threeTypeId = exportParamTypes.value[2] || ''
    }
  }

  const getGoodsTypeFun = async () => {
    await getGoodsType().then((res) => {
      if (res.data.code == 20000) {
        goodsTypeList.value = res.data.data.rows
      }
    })
  }
  const onImportCode = () => {
    router.push({ path: '/code/codeExcelImport' })
  }
  // 查看详细
  const goDetail = (row) => {
    router.push({
      path: `/code/codetail/${row.id}/${row.tableType}`,
      query: { applyState: row.applyState },
    })
  }

  const activeId = ref([])

  /**
   * 创建日期范围选择事件
   * @param {Object} param - 日期选择组件返回值
   * @param {String} param.startDate - 开始日期
   * @param {String} param.endDate - 结束日期
   */
  const handleDateChange = (param: { startDate: string; endDate: string }) => {
    getListParam.value.startTime = param.startDate
    getListParam.value.endTime = param.endDate
    getCodeList()
  }

  /**
   * 出库日期范围选择事件
   * @param {Object} param - 日期选择组件返回值
   * @param {String} param.startDate - 开始日期
   * @param {String} param.endDate - 结束日期
   */
  const handleOutWarehouseDateChange = (param: { startDate: string; endDate: string }) => {
    getListParam.value.snCodeStoreOutboundStartDate = param.startDate
    getListParam.value.snCodeStoreOutboundEndDate = param.endDate
    getCodeList()
  }

  /**
   * 出厂日期范围选择事件
   * @param {Object} param - 日期选择组件返回值
   * @param {String} param.startDate - 开始日期
   * @param {String} param.endDate - 结束日期
   */
  const handleDateChange2 = (param: { startDate: string; endDate: string }) => {
    getListParam.value.dateOfProductionStartTime = param.startDate
    getListParam.value.dateOfProductionEndTime = param.endDate
    getCodeList()
  }

  /**
   * 导出条件的创建日期范围选择
   * @param {Object} param - 日期选择组件返回值
   * @param {String} param.startDate - 开始日期
   * @param {String} param.endDate - 结束日期
   */
  const handleChangeExportParamCreateDateRange = (param: {
    startDate: string
    endDate: string
  }) => {
    exportParam.value.startTime = param.startDate
    exportParam.value.endTime = param.endDate
    getCodeList()
  }

  /**
   * 导出条件的创建日期范围选择
   * @param {Object} param - 日期选择组件返回值
   * @param {String} param.startDate - 开始日期
   * @param {String} param.endDate - 结束日期
   */
  const handleChangeExportParamLeaveFactoryDateRange = (param: {
    startDate: string
    endDate: string
  }) => {
    exportParam.value.dateOfProductionStartTime = param.startDate
    exportParam.value.dateOfProductionEndTime = param.endDate
    getCodeList()
  }

  /**
   * 导出序列号
   */
  const onExportCode = () => {
    exportCodeModalState.value = true
  }

  /**
   * 隐藏导出弹窗
   */
  const hideExportModal = () => {
    exportParam.value = {
      brandId: '',
      code: '',
      dateOfProductionEndTime: '',
      dateOfProductionStartTime: '',
      endTime: '',
      goods: '',
      goodsModel: '',
      goodsName: '',
      goodsSpec: '',
      outboundCode: '',
      sendGoodsNumber: '',
      startTime: '',
      status: 1,
      threeTypeId: '',
      twoTypeId: '',
      type: 1,
      typeId: '',
      storestatus: '',
      snCodeStoreOutboundEndDate: '',
      snCodeStoreOutboundStartDate: '',
      codeSource: '',
      applyState: '',
    }
    exportCodeModalState.value = false
  }

  /**
   * 确认导出
   */
  const onConfirmExport = () => {
    exportLoading.value = true
    codeExportExcel(getListParam.value).then((res) => {
      // 因为前端把responseType: 'blob'放到请求头里，所以当后端响应JSON时也会把JSON转为blob
      // 所以需要将响应的数据转回JSON对象，如果转换成功就说明返回的是JSON，否则则是文件流
      let reader = new FileReader()
      reader.readAsText(res.data)
      reader.onload = function (result) {
        try {
          // 解析对象成功，说明后端返回的是JSON
          let resData = JSON.parse(result.target.result as string)
          ElMessage({
            showClose: true,
            message: resData.message,
            type: resData.code === 61000 ? 'warning' : 'error',
            plain: true,
            duration: 5000,
          })
        } catch (err) {
          // 解析失败，说明后端返回的是文件流
          ElMessage({
            showClose: true,
            message: '序列号数据导出成功',
            type: 'success',
            plain: true,
            duration: 5000,
          })
          const url = window.URL.createObjectURL(new Blob([res.data], { type: '.xlsx' }))
          const link = document.createElement('a')
          link.href = url
          link.download = `序列号档案_${moment(new Date()).format('YYYYMMDD')}.xlsx`
          link.click()
        }
      }
      exportLoading.value = false
    })
  }

  const remoteMethod = _.throttle((val) => {
    if (dataPage.name !== val) {
      dataPage.name = val
      loading2.value = true
      brandPageSelect(dataPage).then((res) => {
        brandData.value = res.data.data.rows
        loading2.value = false
      })
    }
  }, 500)

  // 批量操作勾选
  const changeAll = (val) => {
    if (val) {
      activeId.value = val.map((o) => {
        return {
          id: o.id,
          tableType: o.tableType,
        }
      })
    }
  }
  // 批量操作
  const handleClick = (val) => {
    if (val == 1) {
      if (activeId.value.length == 0) {
        ElMessage({
          type: 'warning',
          message: '请先选择激活的物料！',
          plain: true,
          showClose: true,
          duration: 5000,
        })
        return
      }
      ElMessageBox.confirm('确定激活选择的物料吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        autofocus: false,
        beforeClose: (action: Action, instance: MessageBoxState, done: () => void) => {
          if (action === 'cancel' || action === 'close') {
            done()
          }

          if (action === 'confirm') {
            instance.cancelButtonLoading = true
            instance.confirmButtonLoading = true
            activCode(activeId.value).then((res) => {
              if (res.data.code == 20000) {
                activeId.value = []
                getCodeList()
              }
              ElMessage({
                type: res.data.success ? 'success' : 'error',
                message: res.data.message,
                plain: true,
                showClose: true,
                duration: 5000,
              })
              instance.cancelButtonLoading = false
              instance.confirmButtonLoading = false
              done()
            })
          }
        },
      })
    } else {
      if (!activeId.value) {
        ElMessage({
          type: 'warning',
          message: '请先选择删除的序列号！',
          duration: 5000,
          showClose: true,
          plain: true,
        })
        return
      }
      ElMessageBox.confirm('确定要删除选中的序列号吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error',
        autofocus: false,
        beforeClose: (action: Action, instance: MessageBoxState, done: () => void) => {
          if (action === 'confirm') {
            instance.cancelButtonLoading = true
            instance.confirmButtonLoading = true
            deleteCode(activeId.value).then((res) => {
              ElMessage({
                type: res.data.success ? 'success' : 'error',
                message: res.data.message,
                duration: 5000,
                showClose: true,
                plain: true,
              })
              if (res.data.code == 20000) {
                activeId.value = []
                getCodeList()
              }
              instance.cancelButtonLoading = false
              instance.confirmButtonLoading = false
              done()
            })
          }

          if (action === 'cancel' || action === 'close') {
            done()
          }
        },
      })
    }
  }

  const setTableStyle = () => {
    const headerHeight = headerRef.value ? headerRef.value.scrollHeight : 0
    const paginationHeight = paginationRef.value ? paginationRef.value.scrollHeight : 0
    tableStyle.value.maxHeight = `calc(100% - 24px - ${headerHeight}px - ${paginationHeight}px)`
  }

  /**
   * 获取序列号列表
   */
  const getCodeList = () => {
    getListParam.value.applyState = ''
    if (route.query.status === 'wait-check') {
      getListParam.value.applyState = 0
    }
    if (paginationInstance.value) {
      getListParam.value.limit = paginationInstance.value.size
      getListParam.value.page = paginationInstance.value.current
      getList()
    }
  }

  watch(
    () => route.name,
    (value) => {
      if (value === 'codeList') {
        getCodeList()
      }
    },
  )

  onMounted(() => {
    getCodeList()
    getGoodsTypeFun()
    brandPageSelect(dataPage).then((res) => {
      brandData.value = res.data.data.rows
    })
    typePageSelect(dataPage2).then((res) => {
      typeData.value = res.data.data.rows
    })
    setTableStyle()
    window.addEventListener('resize', setTableStyle)
  })

  onUnmounted(() => {
    window.removeEventListener('resize', setTableStyle)
  })
</script>

<style scoped lang="scss">
  .codes_container {
    height: calc(100vh - 92px);
    box-sizing: border-box;
    padding: 12px;

    .body {
      box-sizing: border-box;
      padding: 12px;
      background-color: #fff;
      height: 100%;
      display: flex;
      flex-direction: column;
      row-gap: 12px;

      .header {
        display: flex;
        justify-content: space-between;
        flex-wrap: wrap;
        row-gap: 10px;
        column-gap: 5px;
        .btn_group {
          display: flex;
          column-gap: 5px;
        }

        .search {
          display: flex;
          flex-wrap: wrap;
          row-gap: 10px;
          column-gap: 5px;
        }
      }

      .table-footer {
        flex: 1;
        height: 0;
        display: flex;
        flex-direction: column;
        row-gap: 12px;

        .table {
          max-height: calc(100% - 40px);
        }

        .pagination {
          display: flex;
          justify-content: flex-end;
        }
      }
    }
  }

  .export_code_modal_form_content {
    display: flex;
    gap: 12px;
    flex-direction: column;
    padding: 0 112px;

    .date_range {
      display: flex;
      justify-content: space-between;
      gap: 5px;
    }

    .form_item_container {
      display: grid;
      grid-template-columns: repeat(2, 1fr);
      column-gap: 5px;
    }

    .grid-layout {
      display: grid;
      grid-template-columns: repeat(2, 244px);
      justify-content: space-between;
      row-gap: 12px;

      :deep(.el-input) {
        width: 100%;
      }
    }
  }

  .date-range {
    :deep(.el-input__wrapper) {
      height: 28px !important;
    }
  }

  .export_code_modal {
    display: flex;
    flex-direction: column;
    row-gap: 12px;
  }

  .export-btn {
    display: flex;
    justify-content: flex-end;
    margin-top: 2vh;
  }

  .date-range {
    display: flex;
    gap: 5px;

    :deep(.el-input__wrapper) {
      box-sizing: border-box;
    }

    .start-date,
    .end-date {
      flex: 1;
    }
  }
</style>
